import member from '@src/store/member'
import base from '@src/store/base'
import {
  getCouponList,
  cartList
} from '@src/api/coupon';
import {
  storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import router from '@src/router'
import dayjs from "dayjs";

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'memberName', 'categoryName', 'categoryImage'],
    actions: ['getBaseInfo'],
  }, {
    store: base,
    fields: ['themeColor', 'businessName', 'themeTitleColor', 'businessLogo']
  }],
  data: {
    login: false,
    navWChoose: 0,
    page: 1,
    pageSize: 10,
    listData: [],
    //1:全部 2：即将过期
    activeCard: 1,
    cardList: [],
    //即将过期list
    pastList: [],
    couponLen: 0,
    //即将过期的券
    pastCouponList: []
  },
  methods: {
    onPullDownRefresh() {
      this.initLoadingData();
    },
    onReachBottom() {
      if (this.data.hasNextPage) {
        this.setData({
          page: this.data.page + 1
        })
        this.fetchData();
      }
    },
    onLoad(options) {
      if (options && options.navWChoose) {
        this.setData({
          'navWChoose': Number(options.navWChoose)
        })
      }
      this.$scrollTop = this.selectComponent("#scroll-top");
    },
    onPageScroll(res) {
      this.$scrollTop.onPageScroll(res);
    },
    onLogin() {
      if (this.data.isMember == null) {
        this.getBaseInfo();
      }
      this.fetchData();
      this.cartListFunc()
      this.setData({
        login: true
      })

    },
    navItemClick(e) {
      let itemIndex = e.currentTarget.dataset.index
      //0是券 1.卡
      if (itemIndex === 1) {
        this.setData({
          navWChoose: itemIndex
        });
        this.cartListFunc()
      } else {
        this.setData({
          navWChoose: itemIndex
        })
        this.initLoadingData();
      }
      this.setData({
        activeCard: 1
      })
    },
    //切换卡tab
    checkoutTab(e) {
      let index = e.currentTarget.dataset.index;
      if (index != this.data.activeCard) {
        this.setData({
          activeCard: index
        })
        //是券的时候
        if (this.data.navWChoose === 0) {
          if (this.data.activeCard === 1) {
            this.setData({
              showCouponList: this.data.listData
            })
          } else {
            this.setData({
              showCouponList: this.data.pastCouponList
            })
          }
        }
      }

      console.log('this.data.activeCard--', this.data.activeCard)
    },
    //获取卡列表
    cartListFunc() {
      let data = {
        status: 1,
        cardType: null
      };
      cartList(data).then(res => {
        if (res.code == 0) {
          this.setData({
            cardList: res.data,
          })
          this.handlePastList()
        }
      })
    },
    //获取即将过期卡列表
    handlePastList() {
      let cardList = this.data.cardList;
      let arr = [];
      cardList.forEach(item => {
        if (item.expireAfter && item.expireAfter < 8) {
          arr.push(item)
        }
      })
      this.setData({
        pastList: arr,
      })

    },
    //进入卡详情
    intoCardDetail(e) {
      console.log('e', e)
      let cardNo = e.currentTarget.dataset.no;
      router.push({
        name: 'member/couponDetailNew',
        params: {
          type: 2,
          code: cardNo
        }
      })

    },
    //进入旧卡详情
    navigateToCard() {
      router.push({
        name: 'member/memberCardDetail'
      })
    },
    initLoadingData() {
      if (!this.data.login) {
        return;
      }
      /*初始化状态*/
      this.setData({
        isHasData: true,
        page: 1,
        pageSize: 10,
        listData: []
      })
      this.getBaseInfo()
      this.fetchData();
      this.cartListFunc();
    },
    //进入领券中心页面
    goExchangeCoupon() {
      router.push({
        name: 'member/exchangeCoupon'
      })
    },
    goCouponCenter() {
      router.push({
        name: 'member/couponCenter'
      })
    },

    fetchData() {
      let params = {
        status: 1,
        page: this.data.page,
        pageSize: this.data.pageSize
      };
      this.setData({
        loading: true
      })
      getCouponList(params).then(res => {
        wx.stopPullDownRefresh();
        if (res.code === 0) {
          let list = this.toUpperCaseFunc(res.data.list);
          list = this.expireAfterFunc(list);
          let listData = this.data.listData;
          listData = listData.concat(this.parseCouponList(list));
          this.setData({
            listData: listData,
            showCouponList: listData,
            hasNextPage: res.data.hasNextPage,
            loading: false,
            couponLen: listData.length
          })
          if (this.data.activeCard == 2) {
            this.setData({
              showCouponList: this.data.pastCouponList
            })
            console.log('showCouponList--2', this.data.showCouponList)
          }
        } else {
          this.setData({
            loading: false
          })
        }
      }).catch((error) => {
        console.error("error", error)
        this.setData({
          loading: false
        })
      })
    },
    //兼容新 旧券 大小写和类型问题
    toUpperCaseFunc(list) {
      if (list.length > 0) {
        let str = /^8128\d{16,20}$/
        list.forEach(item => {
          // extend:1新券，extend:2 旧券
          if (str.test(item.customerCoupon.couponCode)) {
            item.extend = 1;
          } else {
            item.extend = 2;
          }
          let type = item.customerCoupon.couponType;
          item.type = type;
          if (type == 'cash' || type == 'cash_wx_busi' || type == 'cash_wx_pay') {
            item.customerCoupon.couponType = 'CASH';
          } else if (type == 'discount' || type == 'discount_wx_busi') {
            item.customerCoupon.couponType = 'DISCOUNT';
          } else if (type == 'exchange') {
            item.customerCoupon.couponType = 'GENERAL';
          }
          item.customerCoupon.couponType = item.customerCoupon.couponType.toUpperCase();
        })
        console.log('list', list)
        return list;
      } else {
        return []
      }
    },
    //计算即将过期的券
    expireAfterFunc(list) {
      var day1 = Date.parse(new Date());
      let arr = []
      if (list.length > 0) {
        list.forEach(item => {
          if (item.customerCoupon) {
            let expireTime = item.customerCoupon.expireTime
            let day2 = new Date(expireTime.replace(/-/g, '/')).getTime();
            item.after = (day2 - day1) / (1000 * 60 * 60 * 24);
            if (item.after < 30) {
              arr.push(item)
            }
          }
        })
        this.setData({
          pastCouponList: arr
        })
        return list;
      }

      return [];
    },
    navigateToDetail(e) {
      console.log('e', e)
      let name = e.currentTarget.dataset.name;
      let params = e.currentTarget.dataset.params;
      let type = e.currentTarget.dataset.type;
      params.type = 1;
      let str = /^8128\d{16}$/
      // let str = "^(8128|8130)\\d{16}$";
      //匹配新券 跳新详情页
      if (str.test(params.couponCode) || type == 'cash_wx_pay') {
        router.push({
          name: 'member/couponDetailNew',
          params: params
        })
      } else {
        router.push({
          name: name,
          params: params
        })
      }
    },
    parseCouponList(list) {
      list = list.map(value => {
        let customerCoupon = value.customerCoupon;
        let nowTime = dayjs();
        let day = dayjs(customerCoupon.expireTime).diff(nowTime, 'day');
        let effective = dayjs(customerCoupon.effectiveTime).diff(nowTime, 'day');
        if (day === 0) {
          value.expireTag = "今天即将过期";
        }
        if (day < 0) {
          value.expireTag = "已过期";
        }
        value.day = day;
        value.effective = effective
        value.dillExpireTime = dayjs(customerCoupon.expireTime).subtract(1, "second").format("YYYY-MM-DD");
        value.effectiveTime = dayjs(customerCoupon.effectiveTime).format("YYYY-MM-DD");
        if (customerCoupon.couponType === "CASH") {
          let reduceCost = customerCoupon.reduceCost / 100;
          let reduceCostArr = reduceCost.toString().split(".");
          value.balanceBefore = reduceCostArr[0];
          if (reduceCostArr.length > 1) {
            value.afterBalance = reduceCostArr[1];
          }
        } else if (customerCoupon.couponType === "DISCOUNT") {
          //处理折扣字段
          let reduceDiscount = customerCoupon.discount / 10;
          let reduceDiscountArr = reduceDiscount.toString().split(".");
          if (reduceDiscountArr.length > 1) {
            value.discountBefore = reduceDiscountArr[0];
            value.discountAfter = reduceDiscountArr[1];
          } else {
            value.discountBefore = reduceDiscountArr[0];
            value.discountAfter = 0;
          }
        }
        return value;
      });
      return list;
    },
    navigateToHome() {
      router.push({
        path: 'pages/index/main',
      })
    }
  }
})